package com.cskaoyan.wordmemorize.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.cskaoyan.wordmemorize.dao.entity.ExampleSentenceDO;
import com.cskaoyan.wordmemorize.dao.entity.VocChapBookDO;
import com.cskaoyan.wordmemorize.dao.entity.VocDO;
import com.cskaoyan.wordmemorize.dao.entity.VocMeaningDO;
import com.cskaoyan.wordmemorize.dao.mapper.ExampleSentenceMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocChapBookMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocMeaningMapper;
import com.cskaoyan.wordmemorize.dto.admin.VocExcelDTO;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import java.util.List;

/**
 * Excel 导入监听器，用于导入单词数据
 * 使用 Mapper 操作数据库，不依赖 Spring 管理
 * 支持批量插入
 */
@Slf4j
@Getter
@Setter
public class VocExcelListener implements ReadListener<VocExcelDTO> {

    // 每批插入 100 条，防止内存溢出
    private static final int BATCH_COUNT = 100;

    // 记录处理的总行数
    private int totalCount = 0;

    // 用于缓存待插入的数据
    private List<VocDO> vocList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<VocMeaningDO> vocMeaningList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<ExampleSentenceDO> exampleSentenceList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<VocChapBookDO> vocChapBookList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    // 注入的 Mapper
    private final VocMapper vocMapper;
    private final VocMeaningMapper vocMeaningMapper;
    private final ExampleSentenceMapper exampleSentenceMapper;
    private final VocChapBookMapper vocChapBookMapper;

    /**
     * 构造函数注入所需的 Mapper
     */
    public VocExcelListener(VocMapper vocMapper,
                            VocMeaningMapper vocMeaningMapper,
                            ExampleSentenceMapper exampleSentenceMapper,
                            VocChapBookMapper vocChapBookMapper) {
        this.vocMapper = vocMapper;
        this.vocMeaningMapper = vocMeaningMapper;
        this.exampleSentenceMapper = exampleSentenceMapper;
        this.vocChapBookMapper = vocChapBookMapper;
    }

//    // 新增方法：供外部获取处理条数
//    public int getTotalCount() {
//        return totalCount;
//    }

    /**
     * 每解析一行 Excel 数据，都会调用一次该方法
     */
    @Override
    public void invoke(VocExcelDTO vocExcelDTO, AnalysisContext analysisContext) {
        int rowIndex = analysisContext.readRowHolder().getRowIndex();
        log.info("开始处理第 {} 行数据", rowIndex + 1);

        // 每次处理一行，增加计数器
        totalCount++;

        // Step 1: 构建主表 VocDO
        VocDO voc = new VocDO();
        voc.setContent(vocExcelDTO.getContent());
        voc.setUkPhonetic(vocExcelDTO.getUkPhonetic());
        voc.setUsPhonetic(vocExcelDTO.getUsPhonetic());
        voc.setUkPronounciation(vocExcelDTO.getUkPronounciation());
        voc.setUsPronounciation(vocExcelDTO.getUsPronounciation());

        vocList.add(voc);
        log.info("缓存单词：{}", voc.getContent());


        // Step 2: 构建释义表 VocMeaningDO
        String[] meaningLines = vocExcelDTO.getInterpretations().split("\n");

        for (String line : meaningLines) {
            String[] parts = line.split("\\.", 2); // 分割词性和释义
            if (parts.length == 2) {
                VocMeaningDO meaning = new VocMeaningDO();
                meaning.setVocId(voc.getId()); // 注意：voc.getId() 此时为 null，插入主表后才能设置
                meaning.setType(parts[0].trim());
                meaning.setInterContent(parts[1].trim());

                vocMeaningList.add(meaning);
                log.info("缓存释义：{}", line);
            }
        }


        // Step 3: 构建例句表 ExampleSentenceDO
        String[] exampleLines = vocExcelDTO.getExampleSentences().split("\n");

        for (int i = 0; i < exampleLines.length; i += 2) {
            if (i + 1 < exampleLines.length) {
                ExampleSentenceDO example = new ExampleSentenceDO();
                example.setVocId(voc.getId());
                example.setContent(exampleLines[i].trim());
                example.setMeaning(exampleLines[i + 1].trim());

                exampleSentenceList.add(example);
                log.info("缓存例句：{}", example.getContent());
            }
        }


        // Step 4: 构建书籍章节表 VocChapBookDO
        String[] bookInfo = vocExcelDTO.getBookInfos().split("#");

        if (bookInfo.length == 2) {
            VocChapBookDO chapBook = new VocChapBookDO();
            chapBook.setId(IdWorker.getId()); // 新增：设置主键
            chapBook.setVocId(voc.getId());
            chapBook.setVocName(voc.getContent());
            chapBook.setBookName(bookInfo[0].trim());
            chapBook.setChapterName(bookInfo[1].trim());

            vocChapBookList.add(chapBook);
            log.info("缓存书籍信息：{}", vocExcelDTO.getBookInfos());
        }

        // 达到批量数量，执行插入
        if (vocList.size() >= BATCH_COUNT) {
            saveData();
            clearCache();
        }
    }

    /**
     * 所有数据解析完成后调用，插入剩余数据
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData(); // 插入剩余数据
        log.info("所有数据解析完成！");
    }

    /**
     * 执行批量插入操作
     */
    private void saveData() {
        log.info("开始批量插入 {} 条单词数据", vocList.size());

        // Step 1: 插入单词主表
        if (!vocList.isEmpty()) {
            vocMapper.batchInsert(vocList); // 批量插入方法
        }

        // Step 2: 插入释义表（需要先获取 vocId）
        if (!vocMeaningList.isEmpty()) {
            for (int i = 0; i < vocList.size(); i++) {
                VocDO voc = vocList.get(i);
                for (VocMeaningDO meaning : vocMeaningList) {
                    if (meaning.getVocId() == null && meaning.getInterContent().startsWith(voc.getContent())) {
                        meaning.setVocId(voc.getId());
                    }
                }
            }
            vocMeaningMapper.batchInsert(vocMeaningList);
        }

        // Step 3: 插入例句表
        if (!exampleSentenceList.isEmpty()) {
            for (int i = 0; i < vocList.size(); i++) {
                VocDO voc = vocList.get(i);
                for (ExampleSentenceDO example : exampleSentenceList) {
                    if (example.getVocId() == null && example.getContent().startsWith(voc.getContent())) {
                        example.setVocId(voc.getId());
                    }
                }
            }
            exampleSentenceMapper.batchInsert(exampleSentenceList);
        }

        // Step 4: 插入书籍章节表
        if (!vocChapBookList.isEmpty()) {
            for (int i = 0; i < vocList.size(); i++) {
                VocDO voc = vocList.get(i);
                for (VocChapBookDO chapBook : vocChapBookList) {
                    if (chapBook.getVocId() == null && chapBook.getVocName().equals(voc.getContent())) {
                        chapBook.setVocId(voc.getId());
                    }
                }
            }
            vocChapBookMapper.batchInsert(vocChapBookList);
        }

        log.info("数据插入完成");
    }

    /**
     * 清空缓存列表
     */
    private void clearCache() {
        vocList.clear();
        vocMeaningList.clear();
        exampleSentenceList.clear();
        vocChapBookList.clear();
    }
}